package ims.db.view.product;

import ims.beans.Product;
import ims.constants.IMSConstants;
import ims.db.AbstractDAO;
import ims.db.AbstractDbRequest;
import ims.db.AbstractDbResponse;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;

public class ViewProductDAO extends AbstractDAO {

	public ViewProductDAO() throws ClassNotFoundException, SQLException {
		super();
	}

	@Override
	public AbstractDbResponse execute(AbstractDbRequest dbRequest) 
	{
		ViewProductDbResponse response = new ViewProductDbResponse();
		ViewProductDbRequest request = (ViewProductDbRequest)dbRequest;
        try 
        {
        	Statement stmt = conn.createStatement();
        	StringBuffer sql = new StringBuffer();
        	if(request.isViewAll())
        		sql.append("select p.pid, p.prodTypeId, p.price, p.prodDesc, pt.prodTypeId, pt.productType from Product p, ProductType pt where p.prodTypeId=pt.prodTypeId order by p.pid");
        	else
        		sql.append("select p.pid, p.prodTypeId, p.price, p.prodDesc, pt.prodTypeId, pt.productType from Product p, ProductType pt where p.prodTypeId=pt.prodTypeId and p.pid ='").append(request.getProdId()).append("'");
        		
        	
    		ResultSet rset = stmt.executeQuery(sql.toString());
    		ArrayList <Product> products = new ArrayList <Product> ();
	        while (rset.next())
	        {
	        	Product product = new Product();
	        	product.setPid(rset.getString(1));
	        	product.setProdType(rset.getString(2));
	        	product.setPrice(rset.getDouble(3));
	        	product.setProdDesc(rset.getString(4));
	        	product.setProdTypeId(rset.getString(5));
	        	product.setProdType(rset.getString(6));
	        	products.add(product);
	        }
	        if (request.isViewAll())
	        {
	        	String lastProdTypeId = products.get(products.size()-1).getPid().substring(1);
	        	int id = Integer.parseInt(lastProdTypeId);
	        	IMSConstants.PROD_ID = ++id;
	        }
	        
	        response.setProducts(products);
	        rset.close();
            stmt.close();
            conn.close();
        } 
        catch (SQLException sqlEx)
        {
        	sqlEx.printStackTrace();
        }
        return response;
	}
}
